<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/24
 * Time: 19:41
 * @link http://www.lmterp.cn
 */

namespace app\common\service\export;


use app\common\library\Tools;
use app\common\model\Orders;
use app\common\model\OrdersDetail;

class Order extends BaseExport
{

    protected $prefix = 'order';

    /**
     * @inheritDoc
     */
    public function getHeader()
    {
        return [
            "orders.order_id" => "订单ID",
            "orders.order_sn"  => "内部订单号",
            "orders.order_no"  => "平台订单号",
            "orders.platform_name" => "平台名称",
            "orders.account_id" => "销售账号",
            "detail.sku" => "内部SKU",
            "detail.platform_sku" => "平台SKU",
            "detail.qty" => "购买数量",
            "detail.price" => "单价",
            "orders.order_status" => "订单状态",
            "orders.is_print" => "是否打印面单",
            "orders.latest_delivery_time" => "最迟发货时间",
            "orders.profit" => "利润",
            "orders.weight" => "重量",
            "orders.prime_cost" => "成本",
            "orders.refund" => "退款金额(人民币)",
            "orders.target_refund" => "退款目标金额",
            "orders.send_status" => "发货状态",
            "orders.order_platform_status" => "订单在平台状态",
            "orders.payment_method" => "支付方式",
            "orders.customs_code" => "客户通关编码",
            "orders.logistics_name" => "物流商",
            "orders.logistics_price" => "物流价格",
            "orders.label_url" => "面单地址",
            "orders.shipping_time" => "发货时间",
            "orders.shipping_method" => "发货方式",
            "orders.shipping_status" => "物流状态",
            "orders.track_num_time" => "更新追踪号时间",
            "orders.track_num" => "追踪号",
            "orders.shipping_price" => "客户支付运费",
            "orders.discount_amount" => "订单优惠金额",
            "orders.commission_cost" => "平台佣金",
            "orders.order_source_create_time" => "平台生成订单时间",
            "orders.order_pay_time" => "订单支付时间",
            "orders.surcharge_price" => "订单附加费",
            "orders.order_price" => "订单价格",
            "orders.total_price" => "订单总价",
            "orders.total_qty" => "订单总数",
            "orders.currency" => "币种",
            "orders.buyer_first_name" => "买家名",
            "orders.buyer_last_name" => "买家姓",
            "orders.consignee" => "收件人",
            "orders.buyer_post_code" => "邮编",
            "orders.buyer_gender" => "性别",
            "orders.buyer_phone" => "电话",
            "orders.buyer_mobile" => "手机",
            "orders.buyer_account" => "买家账号",
            "orders.buyer_fax" => "传真",
            "orders.buyer_email" => "邮箱",
            "orders.buyer_company" => "公司",
            "orders.buyer_country" => "国家",
            "orders.buyer_country_code" => "国家编码",
            "orders.buyer_province" => "省（州）",
            "orders.buyer_city" => "市",
            "orders.buyer_district" => "区",
            "orders.buyer_address_1" => "地址1",
            "orders.buyer_address_2" => "地址2",
            "orders.buyer_address_3" => "地址3",
            "orders.invoice_type" => "发票种类",
            "orders.invoice_title" => "发票抬头",
            "orders.invoice_detail" => "发票内容",
            "orders.platform_remark" => "平台备注",
            "orders.remark" => "订单备注",
            "orders.is_flag_sent" => "标记状态",
            "orders.sent_time" => "标记时间",
            // 订单详情
            "detail.detail_id" => "订单详情ID",
            "detail.product_code" => "商品编码",
            "detail.item_id" => "平台产品id",
            "detail.name" => "产品名称",
            "detail.name_ch" => "产品中文名",
            "detail.attr" => "产品属性",
            "detail.return_qty" => "退货数量",
            "detail.image_url" => "图片地址",
            "detail.url" => "商品在线地址",
            "detail.is_cancel" => "是否取消",
            "detail.is_bundle" => "是否捆绑SKU",
            "detail.declare_en" => "申报英文名",
            "detail.declare_ch" => "申报中文名",
            "detail.declare_price" => "申报价格",
            "detail.customer_remark" => "客户备注",
            "detail.remark" => "订单详情备注",
            "detail.create_time" => "导入时间",
            "detail.create_by" => "导入人",
        ];
    }

    /**
     * @inheritDoc
     */
    public function getData($condition = [])
    {
        $tempField = $this->getField();
        $orderField = $tempField['orders'];
        $detailField = $tempField['detail'];
        list($orderWhere, $detailWhere) = $this->parseWhere($condition);
        $ordersModel = Orders::where($orderWhere)
            ->with([
                "account" => function($query){$query->field(["username", "account_id"]);},
                "admin"   => function($query){$query->field(["id","nickname"]);},
                "detail" => function($query)use($detailWhere){$query->where($detailWhere);},
            ]);
        // 是否需要子查询
       if(!empty($detailWhere))
       {
           $ordersModel->where("order_id", "in", function($query)use($detailWhere)
           {
               $query->table(OrdersDetail::getTable())->where($detailWhere)->field("order_id");
           });
       }
       // 处理输入数据
       $ret = [];
       foreach($ordersModel->select() as $item)
       {
           $nickname = !empty($item->admin->nickname) ? $item->admin->nickname : '系统自动导入';
           $order = $item->toArray();
           $order['account_id'] = $item->account->username;
           $order = Tools::replaceArrayKey($orderField, array_intersect_key($order, $orderField));
           foreach($item->detail as $dkey => $details)
           {
               $detail = $details->toArray();
               $detail['create_by'] = $nickname;
               $detail = Tools::replaceArrayKey($detailField, array_intersect_key($detail, $detailField));
               $ret[] = ($dkey == 0 ? $order : Tools::emptyArray($order)) + $detail;
           }
       }
        $this->sortData($ret);
       return $ret;
    }

    /**
     * 解析订单和订单详情查询条件
     * @param array $condition 查询条件
     * @date 2020/08/29
     * @author longli
     * @return array
     */
    protected function parseWhere($condition = [])
    {
        $orderWhere = $detailWhere = [];
        $inDetail = ['product_code', 'item_id', 'sku', 'platform_sku', 'name_ch', 'name', 'attr', 'qty', 'return_qty', 'price', 'is_cancel', 'declare_en', 'declare_ch'];
        // 遍历查询条件
        foreach($condition as $item)
        {
            $temp = explode('.', $item[0]);
            if(count($temp) == 2)
            {
                $item[0] = $temp[1];
                $temp[0] == 'detail'
                    ? $detailWhere[] = $item
                    : $orderWhere = $item;
            }
            else
            {
                in_array($item[0], $inDetail)
                ? $detailWhere[] = $item
                : $orderWhere[] = $item;
            }
        }
        return [$orderWhere, $detailWhere];
    }
}